package com.swak.netty.exception;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;

import com.swak.Constants;
import com.swak.OS;
import com.swak.exception.BusinessException;
import com.swak.exception.RemotingException;
import com.swak.reactivex.threads.Contexts;
import com.swak.reactivex.transport.Channel;
import com.swak.reactivex.transport.ExchangeChannel;
import com.swak.reactivex.transport.ExchangeHandlerAdapter;
import com.swak.reactivex.transport.ExchangeServer;
import com.swak.reactivex.transport.Exchangers;
import com.swak.reactivex.transport.TransportMode;
import com.swak.reactivex.transport.resources.LoopResources;
import com.swak.registry.URL;
import com.swak.utils.Fmt;
import com.swak.utils.Maps;

/**
 * 这是一款比较通用的基于 TCP 的通信服务
 * 
 * @author 618lf
 */
public class Server extends ExchangeHandlerAdapter {

	private LoopResources resources = Contexts.createEventLoopResources(TransportMode.OS, 1, 2, "Test.EventLoop-",
			false, 2, TimeUnit.SECONDS);

	ExchangeServer server;
	URL url;

	public Server() throws RemotingException {
		Map<String, String> parameters = Maps.newHashMap();
		parameters.put(Constants.Bind_Host, Constants.ANYHOST);
		//parameters.put(Constants.PAYLOAD_KEY, "20480"); // 最大 1024 byte
		parameters.put(Constants.Timeout, "30000"); // 设置一个大一点的超时时间
		this.url = new URL("Test", OS.ip(), 10889, parameters);
		this.server = Exchangers.bind(url, resources, this);
	}

	@Override
	public void received(Channel channel, Object message) throws RemotingException {
		Fmt.out.println(message);
//		Fmt.out.println("服务器 请求 客户端");
//		ExchangeChannel ch = (ExchangeChannel) channel;
//		ch.request(Message.forRequest().setData("反向请求")).whenComplete((r, t) -> {
//			Fmt.out.println("请求结果：" + r);
//			if (t != null) {
//				t.printStackTrace();
//			}
//		});
	}

	@Override
	public CompletionStage<Object> reply(ExchangeChannel channel, Object message) throws RemotingException {
		Fmt.out.println("服务器收到请求：" + message);

		// 1. 回复一个大于客户端的限额的字节数据 -- 客户端响应错误
		// byte[] data = new byte[1024];
		// 2. 回复一个大于服务器端的限额的字节数据 -- 客户端响应错误
		// byte[] data = new byte[2048];
		// 3. 回复异常的数据 -- 已正常的结果返回 (一般认为业务异常不会被框架处理)
		BusinessException exception = new BusinessException();

		return CompletableFuture.completedFuture(exception);
	}

	@Override
	public void caught(Channel channel, Throwable exception) throws RemotingException {
		Fmt.err.println(exception);
	}

	public static void main(String[] args) throws RemotingException {
		new Server();
	}
}
